
angular.module('QualityJudge')

.factory('QualityJudgeMaster', ['$q', '$filter', 'QualityJudgeHttpUtil', function($q, $filter, QualityJudgeHttpUtil) {
    var o = {};
    var _barcodeMasters = null,
        _activeMasterCode = null,
        _activeMaster = null;

    o.getMasters = function (forceUpdate) {
        var defer = $q.defer();

        forceUpdate = !!forceUpdate;
        $q.when(
            (forceUpdate || !_barcodeMasters) ? QualityJudgeHttpUtil.queryMasters() : _barcodeMasters
        ).then(function (masters) {
            defer.resolve(angular.copy(masters));
        }, function (err) {
            defer.reject(err);
        });

        return defer.promise;
    };
    o.setActiveMaster = function (activeMaster) {
        _activeMaster = activeMaster;
    };
    o.setActiveMasterCode = function (activeMasterCode) {
        _activeMasterCode = activeMasterCode;
    };
    o.getActiveMasterCode = function () {
        return _activeMasterCode;
    };
    o.getActiveMaster = function () {
        var defer = $q.defer();

        if (_activeMaster) {
            defer.resolve(angular.copy(_activeMaster));
        } else if (!_activeMasterCode) {
            defer.resolve({});
        } else {
            QualityJudgeHttpUtil.decideScanCode(_activeMasterCode).then(function (result) {
                if (result.BarcodeType === 0) {
                    defer.resolve(result);
                } else {
                    defer.reject({
                        message: '不能识别的条码'
                    });
                }
            }, function (err) {
                defer.reject(err);
            });
        }

        return defer.promise;
    };

    return o;
}]);
